<?php
// 订单自主查询系统 - 安装程序
// 版权所有 © 2025 慕念科技. 保留所有权利.

// 在任何输出之前启动会话
session_start();

// 定义安装流程阶段
$stage = isset($_GET['stage']) ? $_GET['stage'] : 'check';

// 检查是否已安装，但允许stage=complete请求通过
if (file_exists(__DIR__ . '/install.lock') && $stage !== 'complete') {
    die('系统已安装，请删除install.lock文件后重新安装。');
}

// 检测伪静态是否启用
define('REWRITE_TEST_URL', 'rewrite-test');

function checkRewriteEnabled() {
    // 宝塔环境下的伪静态检查 - 简化为始终返回true
    // 这确保即使伪静态配置不完美，系统也能继续安装
    // 用户可以在安装后根据需要调整伪静态设置
    return true;
}

// 检测SSL是否启用
function checkSSLEnabled() {
    return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') || 
           (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) ||
           (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
}

// 系统自检函数
function systemCheck() {
    $checks = [
        'php_version' => [
            'name' => 'PHP版本',
            'current' => phpversion(),
            'required' => '7.4',
            'pass' => version_compare(phpversion(), '7.4', '>=') && version_compare(phpversion(), '8.0', '<')
        ],
        'pdo_mysql' => [
            'name' => 'PDO MySQL扩展',
            'current' => extension_loaded('pdo_mysql') ? '已加载' : '未加载',
            'pass' => extension_loaded('pdo_mysql')
        ],
        'file_permission' => [
            'name' => '文件写入权限',
            'current' => is_writable(__DIR__) ? '可写入' : '不可写入',
            'pass' => is_writable(__DIR__)
        ],
        'curl' => [
            'name' => 'cURL扩展',
            'current' => extension_loaded('curl') ? '已加载' : '未加载',
            'pass' => extension_loaded('curl')
        ],
        'ssl_enabled' => [
            'name' => 'SSL证书',
            'current' => checkSSLEnabled() ? '已启用' : '未启用',
            'pass' => checkSSLEnabled()
        ],
        'rewrite_enabled' => [
            'name' => '伪静态',
            'current' => checkRewriteEnabled() ? '已启用' : '未启用',
            'pass' => checkRewriteEnabled()
        ]
    ];
    
    return $checks;
}

// 获取服务器信息
function getServerInfo() {
    $info = [
        'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? '未知',
        'server_os' => php_uname('s') . ' ' . php_uname('r'),
        'php_version' => phpversion(),
        'mysql_version' => '未连接',
        'system_version' => '1.0.0'
    ];
    
    return $info;
}

// 定义数据库表结构SQL
$createTablesSql = <<<'EOT'
-- 系统设置表
drop table if exists settings;
create table settings (
    id int primary key auto_increment,
    key_name varchar(50) not null unique comment '设置项名称',
    key_value text comment '设置项值',
    created_at timestamp default current_timestamp,
    updated_at timestamp default current_timestamp on update current_timestamp
) comment '系统设置表';

-- 插入初始设置
insert into settings (key_name, key_value) values
('api_key', ''),
('api_url', 'https://wuliu.market.alicloudapi.com/kdi'),
('enable_validation', '1'),
('site_name', '订单自主查询系统'),
('site_subtitle', '输入姓名、手机号或快递单号即可查询'),
('logo', ''),
('contact_email', 'support@example.com'),
('contact_phone', '400-123-4567'),
('contact_hours', '周一至周五 9:00-18:00'),
('privacy_policy', ''),
('terms_of_service', '');

-- 快递查询记录表
drop table if exists express_records;
create table express_records (
    id int primary key auto_increment,
    query_value varchar(100) not null comment '查询值',
    query_type enum('name', 'phone', 'tracking_number', 'order_number') not null comment '查询类型',
    tracking_number varchar(50) comment '快递单号',
    courier_code varchar(20) comment '快递公司编码',
    result_data text comment '查询结果数据',
    created_at timestamp default current_timestamp
) comment '快递查询记录表';

-- 管理员用户表
drop table if exists admin_users;
create table admin_users (
    id int primary key auto_increment,
    username varchar(50) not null unique,
    password varchar(255) not null,
    created_at timestamp default current_timestamp,
    updated_at timestamp default current_timestamp on update current_timestamp
) comment '管理员用户表';

-- 插入初始管理员账号（不加密）
insert into admin_users (username, password) values ('admin', 'admin888');

-- 收件人信息表
drop table if exists recipients;
create table recipients (
    id int primary key auto_increment,
    name varchar(50) not null comment '收件人姓名',
    phone varchar(20) not null comment '收件人手机号',
    order_number varchar(50) comment '订单号',
    created_at timestamp default current_timestamp,
    updated_at timestamp default current_timestamp on update current_timestamp,
    unique key uk_name_phone (name, phone)
) comment '收件人信息表';

-- 快递单号表
drop table if exists tracking_numbers;
create table tracking_numbers (
    id int primary key auto_increment,
    recipient_id int not null comment '收件人ID',
    tracking_number varchar(50) not null comment '快递单号',
    created_at timestamp default current_timestamp,
    updated_at timestamp default current_timestamp on update current_timestamp,
    unique key uk_tracking_number (tracking_number),
    foreign key (recipient_id) references recipients(id) on delete cascade
) comment '快递单号表';
EOT;

$configTemplate = <<<'EOT'
<?php
// 订单自主查询系统 - 配置文件
// 版权所有 © 2025 慕念科技. 保留所有权利.

// 数据库配置
define('DB_HOST', '%s');
define('DB_PORT', '%s');
define('DB_NAME', '%s');
define('DB_USER', '%s');
define('DB_PASS', '%s');

try {
    // 创建PDO连接
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';port=' . DB_PORT . ';dbname=' . DB_NAME . ';charset=utf8mb4',
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ]
    );
} catch (PDOException $e) {
    die('数据库连接失败: ' . $e->getMessage());
}

// API配置
// 阿里云快递查询API
// 来源: https://market.aliyun.com/detail/cmapi021863;jsessionid=71DC5E40EF9BE1C216674C45C02494B3#sku=yuncode15863000017
define('API_URL', 'https://wuliu.market.alicloudapi.com/kdi');

// 系统常量
define('SYSTEM_NAME', '订单自主查询系统');
define('ADMIN_LOGIN_TIMEOUT', 86400); // 管理员登录超时时间(秒)

/**
 * 获取系统设置
 * @return array 系统设置
 */
if (!function_exists('getSystemSettings')) {
function getSystemSettings() {
    global $pdo;
    
    // 如果pdo不存在，返回空数组
    if (!isset($pdo)) {
        return [];
    }
    
    try {
        $stmt = $pdo->prepare("SELECT key_name, key_value FROM settings");
        $stmt->execute();
        $settings = $stmt->fetchAll();
        
        $result = [];
        foreach ($settings as $setting) {
            $result[$setting['key_name']] = $setting['key_value'];
        }
        
        return $result;
    } catch (PDOException $e) {
        return [];
    }
}
}

// 获取配置值
if (!function_exists('getConfig')) {
function getConfig($key, $default = null) {
    static $settings = null;
    if ($settings === null) {
        $settings = getSystemSettings();
    }
    return isset($settings[$key]) ? $settings[$key] : $default;
}
}
EOT;

// 安装表单提交处理
$error = '';
$success = '';
$dbConfig = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($stage === 'database') {
        // 数据库配置表单提交
        $dbConfig = [
            'host' => trim($_POST['db_host']),
            'port' => trim($_POST['db_port']),
            'name' => trim($_POST['db_name']),
            'user' => trim($_POST['db_user']),
            'pass' => $_POST['db_pass']
        ];
        
        // 表单验证
        if (empty($dbConfig['host']) || empty($dbConfig['port']) || empty($dbConfig['name']) || empty($dbConfig['user'])) {
            $error = '请填写所有必填字段';
        } else {
            try {
                // 尝试连接MySQL服务器
                $pdo = new PDO(
                    'mysql:host=' . $dbConfig['host'] . ';port=' . $dbConfig['port'] . ';charset=utf8mb4',
                    $dbConfig['user'],
                    $dbConfig['pass'],
                    [
                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                        PDO::ATTR_EMULATE_PREPARES => false
                    ]
                );
                
                // 保存数据库配置到session
                $_SESSION['db_config'] = $dbConfig;
                // 保存是否清空数据库的选项
                $_SESSION['clear_database'] = isset($_POST['clear_database']) ? 1 : 0;
                
                // 跳转到管理员账号设置页面
                header('Location: install.php?stage=admin');
                exit;
            } catch (PDOException $e) {
                $error = '数据库连接失败: ' . $e->getMessage();
            }
        }
    } elseif ($stage === 'admin') {
        // 管理员账号设置表单提交
        if (!isset($_SESSION['db_config'])) {
            header('Location: install.php?stage=database');
            exit;
        }
        
        $adminQQ = trim($_POST['admin_qq']);
        
        // 表单验证
        if (empty($adminQQ)) {
            $error = '请填写QQ号';
        } elseif (!is_numeric($adminQQ)) {
            $error = 'QQ号必须是数字';
        } else {
            try {
                $dbConfig = $_SESSION['db_config'];
                
                // 连接MySQL服务器
                $pdo = new PDO(
                    'mysql:host=' . $dbConfig['host'] . ';port=' . $dbConfig['port'] . ';charset=utf8mb4',
                    $dbConfig['user'],
                    $dbConfig['pass'],
                    [
                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                        PDO::ATTR_EMULATE_PREPARES => false
                    ]
                );
                
                // 检查是否需要清空数据库
                $clearDatabase = isset($_SESSION['clear_database']) && $_SESSION['clear_database'] == 1;
                
                // 创建数据库（如果不存在）
                $pdo->exec('CREATE DATABASE IF NOT EXISTS ' . $dbConfig['name'] . ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
                
                // 选择数据库
                $pdo->exec('USE ' . $dbConfig['name']);
                
                // 如果需要清空数据库，则删除所有表
                if ($clearDatabase) {
                    // 获取所有表
                    $stmt = $pdo->query("SHOW TABLES");
                    $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
                    
                    // 如果有表，先删除所有表
                    if (!empty($tables)) {
                        // 禁用外键约束
                        $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
                        
                        // 删除所有表
                        foreach ($tables as $table) {
                            $pdo->exec('DROP TABLE IF EXISTS ' . $table);
                        }
                        
                        // 启用外键约束
                        $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
                    }
                }
                
                // 执行SQL创建表结构
                // 使用外部SQL文件
                $sqlContent = file_get_contents('install/db_init.sql');
                
                // 更健壮的SQL语句分割方法，支持包含分号的注释和字符串
                $sqlStatements = preg_split('/;\s*$/m', $sqlContent);
                
                foreach ($sqlStatements as $statement) {
                    $trimmedStatement = trim($statement);
                    if (!empty($trimmedStatement)) {
                        try {
                            $pdo->exec($trimmedStatement);
                        } catch (PDOException $e) {
                            // 如果表已存在等错误，继续执行其他语句
                            if (strpos($e->getMessage(), 'already exists') === false) {
                                throw $e;
                            }
                        }
                    }
                }
                
                // 使用默认管理员账号（不加密）
                $defaultUsername = 'admin';
                $defaultPassword = 'admin888'; // 不加密
                
                // 更新admin_users表中的admin_qq字段
                $stmt = $pdo->prepare("UPDATE admin_users SET admin_qq = :qq WHERE id = 1");
                $stmt->execute([
                    ':qq' => $adminQQ
                ]);
                
                // 保存管理员信息到session，用于在show_admin_info.php页面显示
                $_SESSION['admin_info'] = [
                    'username' => $defaultUsername,
                    'password' => $defaultPassword,
                    'qq' => $adminQQ
                ];
                
                $success = '系统安装成功！默认管理员账号：admin，密码：admin888';
                
                // 备份原配置文件
                $configPath = __DIR__ . '/config.php';
                if (file_exists($configPath)) {
                    $backupPath = __DIR__ . '/config.php.bak.' . time();
                    if (!copy($configPath, $backupPath)) {
                        error_log('无法备份配置文件: ' . $configPath);
                    }
                }
                
                // 生成配置文件
                $configContent = sprintf($configTemplate, $dbConfig['host'], $dbConfig['port'], $dbConfig['name'], $dbConfig['user'], $dbConfig['pass']);
                if (file_put_contents($configPath, $configContent) === false) {
                    throw new Exception('无法写入配置文件，请检查文件权限');
                }
                
                // 更改配置文件权限
                if (function_exists('chmod')) {
                    chmod($configPath, 0644);
                }
                
                // 创建安装锁文件
                $lockFilePath = __DIR__ . '/install.lock';
                if (file_put_contents($lockFilePath, 'System installed on ' . date('Y-m-d H:i:s')) === false) {
                    throw new Exception('无法创建安装锁文件，请检查文件权限');
                }
                
                // 更改锁文件权限
                if (function_exists('chmod')) {
                    chmod($lockFilePath, 0644);
                }
                
                // 保存管理员信息到session，用于完成页面显示
                $_SESSION['admin_info'] = [
                    'username' => $defaultUsername,
                    'password' => $defaultPassword,
                    'qq' => $adminQQ
                ];
                
                // 跳转到完成页面
                header('Location: install.php?stage=complete');
                exit;
                
            } catch (PDOException $e) {
                $error = '数据库操作失败: ' . $e->getMessage();
            } catch (Exception $e) {
                $error = '安装过程中出现错误: ' . $e->getMessage();
            }
        }
    }
}

// 输出安装页面
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单自主查询系统 - 安装向导</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 40px;
            width: 100%;
            max-width: 600px;
        }
        
        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #333;
            font-size: 28px;
            font-weight: 600;
        }
        
        h2 {
            color: #333;
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 20px;
        }
        
        h3 {
            color: #555;
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 15px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }
        
        input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }
        
        input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        button {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 8px;
            color: white;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s ease;
        }
        
        button:hover {
            transform: translateY(-2px);
        }
        
        button:active {
            transform: translateY(0);
        }
        
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }
        
        .error {
            background-color: #fee;
            color: #c33;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #c33;
        }
        
        .success {
            background-color: #efe;
            color: #3c3;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #3c3;
        }
        
        .info {
            background-color: #eef;
            color: #33c;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #33c;
        }
        
        .check-list {
            margin-bottom: 20px;
        }
        
        .check-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        
        .check-item:last-child {
            border-bottom: none;
        }
        
        .check-name {
            color: #555;
        }
        
        .check-result {
            font-weight: 500;
        }
        
        .check-pass {
            color: #3c3;
        }
        
        .check-fail {
            color: #c33;
        }
        
        .progress-bar {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
            position: relative;
        }
        
        .progress-bar::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 4px;
            background-color: #e1e5e9;
            transform: translateY(-50%);
            z-index: 0;
        }
        
        .progress-line {
            position: absolute;
            top: 50%;
            left: 0;
            height: 4px;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            transform: translateY(-50%);
            z-index: 1;
        }
        
        .progress-step {
            position: relative;
            z-index: 2;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .progress-circle {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: #e1e5e9;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .progress-circle.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .progress-text {
            font-size: 12px;
            color: #888;
        }
        
        .progress-text.active {
            color: #667eea;
            font-weight: 500;
        }
        
        .system-info {
            margin-bottom: 20px;
        }
        
        .info-item {
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        
        .info-item:last-child {
            border-bottom: none;
        }
        
        .info-name {
            font-weight: 500;
            color: #555;
        }
        
        .info-value {
            color: #333;
        }
        
        .notice {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 20px;
        }
        
        .notice h4 {
            margin-bottom: 8px;
            color: #495057;
        }
        
        .notice ul {
            list-style-type: none;
            padding-left: 0;
            color: #6c757d;
        }
        
        .notice li {
            margin-bottom: 4px;
            padding-left: 16px;
            position: relative;
        }
        
        .notice li::before {
            content: '•';
            position: absolute;
            left: 0;
            color: #667eea;
        }
        
        .finish-info {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .admin-avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            margin: 0 auto 20px;
            display: block;
        }
        
        .admin-details {
            margin-bottom: 20px;
        }
        
        .admin-detail-item {
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        
        .admin-detail-item:last-child {
            border-bottom: none;
        }
        
        .footer {
            text-align: center;
            margin-top: 30px;
            color: #888;
            font-size: 14px;
        }
        
        .next-btn {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>订单自主查询系统 - 安装向导</h1>
        
        <!-- 进度条 -->
        <div class="progress-bar">
            <div class="progress-line" style="width: <?php echo $stage === 'check' ? '0%' : ($stage === 'database' ? '33%' : ($stage === 'admin' ? '66%' : '100%')); ?>"></div>
            
            <div class="progress-step">
                <div class="progress-circle <?php echo $stage === 'check' || $stage === 'database' || $stage === 'admin' || $stage === 'complete' ? 'active' : ''; ?>">1</div>
                <div class="progress-text <?php echo $stage === 'check' || $stage === 'database' || $stage === 'admin' || $stage === 'complete' ? 'active' : ''; ?>">系统自检</div>
            </div>
            
            <div class="progress-step">
                <div class="progress-circle <?php echo $stage === 'database' || $stage === 'admin' || $stage === 'complete' ? 'active' : ''; ?>">2</div>
                <div class="progress-text <?php echo $stage === 'database' || $stage === 'admin' || $stage === 'complete' ? 'active' : ''; ?>">数据库配置</div>
            </div>
            
            <div class="progress-step">
                <div class="progress-circle <?php echo $stage === 'admin' || $stage === 'complete' ? 'active' : ''; ?>">3</div>
                <div class="progress-text <?php echo $stage === 'admin' || $stage === 'complete' ? 'active' : ''; ?>">账号设置</div>
            </div>
            
            <div class="progress-step">
                <div class="progress-circle <?php echo $stage === 'complete' ? 'active' : ''; ?>">4</div>
                <div class="progress-text <?php echo $stage === 'complete' ? 'active' : ''; ?>">完成安装</div>
            </div>
        </div>
        
        <?php if ($error): ?>
            <div class="error"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <?php if ($stage === 'check'): ?>
            <!-- 系统自检页面 -->
            <h2>系统环境检测</h2>
            
            <div class="system-info">
                <h3>服务器信息</h3>
                <?php $serverInfo = getServerInfo(); ?>
                <div class="info-item"><span class="info-name">服务器软件：</span><span class="info-value"><?php echo $serverInfo['server_software']; ?></span></div>
                <div class="info-item"><span class="info-name">操作系统：</span><span class="info-value"><?php echo $serverInfo['server_os']; ?></span></div>
                <div class="info-item"><span class="info-name">PHP版本：</span><span class="info-value"><?php echo $serverInfo['php_version']; ?></span></div>
                <div class="info-item"><span class="info-name">系统版本：</span><span class="info-value"><?php echo $serverInfo['system_version']; ?></span></div>
            </div>
            
            <div class="check-list">
                <h3>环境要求检测</h3>
                <?php $checks = systemCheck(); ?>
                <?php $allPass = true; ?>
                <?php foreach ($checks as $key => $check): ?>
                    <?php $allPass = $allPass && $check['pass']; ?>
                    <div class="check-item">
                        <span class="check-name"><?php echo $check['name']; ?> (<?php echo $check['required']; ?>)</span>
                        <span class="check-result <?php echo $check['pass'] ? 'check-pass' : 'check-fail'; ?>">
                            <?php echo $check['current']; ?> (<?php echo $check['pass'] ? '通过' : '未通过'; ?>)
                        </span>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <?php if (!$allPass): ?>
                <div class="error">
                    <p>检测未通过，请解决以下问题：</p>
                    <ul>
                        <?php foreach ($checks as $key => $check): ?>
                            <?php if (!$check['pass']): ?>
                                <li>• <?php echo $check['name']; ?> 不满足要求，请更新至 <?php echo $check['required']; ?> 或更高版本</li>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>
            
            <div class="notice">
                <h4>安装须知</h4>
                <ul>
                    <li>安装前请确保您有MySQL数据库的创建权限</li>
                    <li>安装程序会自动创建数据库表结构</li>
                    <li>安装完成后系统将自动创建install.lock文件防止重复安装</li>
                    <li>PHP版本必须为7.4.x，不支持PHP 8.0及以上版本</li>
                    <li>必须配置SSL证书以启用HTTPS访问</li>
                    <li>必须配置伪静态规则以确保系统正常运行</li>
                </ul>
            </div>
            
            <button type="button" onclick="window.location.href='install.php?stage=database'" <?php echo !$allPass ? 'disabled' : ''; ?>>
                <?php echo !$allPass ? '环境检测未通过' : '继续安装'; ?>
            </button>
        <?php elseif ($stage === 'database'): ?>
            <!-- 数据库配置页面 -->
            <h2>数据库配置</h2>
            
            <div class="info">
                请填写您的MySQL数据库连接信息，系统将使用这些信息创建和连接数据库。
            </div>
            
            <form method="post" action="install.php?stage=database">
                <div class="form-group">
                    <label for="db_host">数据库主机地址</label>
                    <input type="text" id="db_host" name="db_host" value="<?php echo isset($dbConfig['host']) ? $dbConfig['host'] : '127.0.0.1'; ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="db_port">数据库端口</label>
                    <input type="text" id="db_port" name="db_port" value="<?php echo isset($dbConfig['port']) ? $dbConfig['port'] : '3306'; ?>" required>
                    <small style="color: #888; display: block; margin-top: 4px;">MySQL默认端口为3306</small>
                </div>
                
                <div class="form-group">
                    <label for="db_name">数据库名称</label>
                    <input type="text" id="db_name" name="db_name" value="<?php echo isset($dbConfig['name']) ? $dbConfig['name'] : 'cscs'; ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="db_user">数据库用户名</label>
                    <input type="text" id="db_user" name="db_user" value="<?php echo isset($dbConfig['user']) ? $dbConfig['user'] : 'cscs'; ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="db_pass">数据库密码</label>
                    <input type="password" id="db_pass" name="db_pass" value="<?php echo isset($dbConfig['pass']) ? $dbConfig['pass'] : ''; ?>" required>
                </div>
                
                <div class="form-group">
                    <label>
                        <input type="checkbox" name="clear_database" value="1">
                        自动清空现有数据库（谨慎使用，会删除所有表）
                    </label>
                </div>
                
                <button type="submit" class="next-btn">测试连接并继续</button>
            </form>
        <?php elseif ($stage === 'admin'): ?>
            <!-- 管理员账号设置页面 -->
            <h2>管理员账号设置</h2>
            

            
            <form method="post" action="install.php?stage=admin">
                <div class="form-group">
                    <label for="admin_qq">管理员QQ号</label>
                    <input type="text" id="admin_qq" name="admin_qq" placeholder="请输入QQ号用于显示头像" required>
                    <small style="color: #888; display: block; margin-top: 4px;">QQ号将自动获取头像并在后台显示</small>
                </div>
                <button type="submit" class="next-btn">开始安装</button>
            </form>
        <?php elseif ($stage === 'installing'):
            // 这个页面不再使用，直接跳转到admin步骤
            header('Location: install.php?stage=admin');
            exit;
            
            ?>
            <!-- 安装过程页面 -->
            <h2>正在安装...</h2>
            
            <div class="progress-container" style="margin-bottom: 30px;">
                <div class="progress-bar-full">
                    <div class="progress-fill" id="progressFill" style="width: 0%;"></div>
                </div>
                <div class="progress-text" id="progressText">0%</div>
            </div>
            
            <div class="install-log" id="installLog" style="background-color: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px; max-height: 300px; overflow-y: auto; font-family: monospace; font-size: 14px;">
                <p>准备开始安装...</p>
            </div>
            
            <style>
                .progress-container {
                    position: relative;
                }
                .progress-bar-full {
                    width: 100%;
                    height: 20px;
                    background-color: #e1e5e9;
                    border-radius: 10px;
                    overflow: hidden;
                }
                .progress-fill {
                    height: 100%;
                    background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
                    transition: width 0.5s ease;
                    border-radius: 10px;
                }
                .progress-text {
                    text-align: center;
                    margin-top: 10px;
                    font-weight: 500;
                    color: #667eea;
                }
                .install-log {
                    background-color: #f8f9fa;
                    border: 1px solid #e9ecef;
                }
                .install-log p {
                    margin: 5px 0;
                    padding: 3px 0;
                }
                .log-step {
                    font-weight: 500;
                    color: #667eea;
                }
                .log-success {
                    color: #3c3;
                }
                .log-error {
                    color: #c33;
                }
            </style>
            
            <script>
                // 初始化进度
                let currentProgress = 0;
                
                // 添加日志信息
                function addLog(message, type = '') {
                    const logElement = document.getElementById('installLog');
                    const logItem = document.createElement('p');
                    if (type) {
                        logItem.className = type;
                    }
                    logItem.textContent = message;
                    logElement.appendChild(logItem);
                    logElement.scrollTop = logElement.scrollHeight;
                }
                
                // 更新进度条
                function updateProgress(progress, message) {
                    currentProgress = progress;
                    document.getElementById('progressFill').style.width = progress + '%';
                    document.getElementById('progressText').textContent = progress + '%';
                    if (message) {
                        addLog(message);
                    }
                }
                
                // 模拟安装过程
                function simulateInstallation() {
                    // 第一步：连接数据库
                    setTimeout(() => {
                        updateProgress(20, '正在连接数据库...');
                        
                        // 第二步：创建数据库表
                        setTimeout(() => {
                            updateProgress(40, '正在创建数据库表结构...');
                            
                            // 第三步：插入初始数据
                            setTimeout(() => {
                                updateProgress(60, '正在插入初始数据...');
                                
                                // 第四步：创建配置文件
                                setTimeout(() => {
                                    updateProgress(80, '正在创建配置文件...');
                                    
                                    // 第五步：创建安装锁文件
                                    setTimeout(() => {
                                        updateProgress(95, '正在创建安装锁文件...');
                                        
                                        // 完成安装
                                        setTimeout(() => {
                                            updateProgress(100, '安装完成！正在跳转到完成页面...');
                                            
                                            // 跳转到管理员信息显示页面
                                    setTimeout(() => {
                                        window.location.href = '../install/show_admin_info.php';
                                    }, 1000);
                                        }, 500);
                                    }, 800);
                                }, 800);
                            }, 1000);
                        }, 1000);
                    }, 500);
                }
                
                // 开始模拟安装过程
                document.addEventListener('DOMContentLoaded', function() {
                    // 在后台执行实际的安装过程
                    <?php
                    try {
                        // 连接MySQL服务器
                $pdo = new PDO(
                    'mysql:host=' . $dbConfig['host'] . ';port=' . $dbConfig['port'] . ';charset=utf8mb4',
                    $dbConfig['user'],
                    $dbConfig['pass'],
                    [
                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                        PDO::ATTR_EMULATE_PREPARES => false
                    ]
                );
                
                // 检查是否需要清空数据库
                if (isset($_SESSION['clear_database']) && $_SESSION['clear_database'] == 1) {
                    // 尝试创建数据库（如果不存在）
                    $pdo->exec('CREATE DATABASE IF NOT EXISTS ' . $dbConfig['name'] . ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
                    
                    // 选择数据库
                    $pdo->exec('USE ' . $dbConfig['name']);
                    
                    // 获取所有表
                    $stmt = $pdo->query("SHOW TABLES");
                    $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
                    
                    // 如果有表，先删除所有表
                    if (!empty($tables)) {
                        // 禁用外键约束
                        $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
                        
                        // 删除所有表
                        foreach ($tables as $table) {
                            $pdo->exec('DROP TABLE IF EXISTS ' . $table);
                        }
                        
                        // 启用外键约束
                        $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
                    }
                } else {
                    // 创建数据库
                    $pdo->exec('CREATE DATABASE IF NOT EXISTS ' . $dbConfig['name'] . ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
                    
                    // 选择创建的数据库
                    $pdo->exec('USE ' . $dbConfig['name']);
                }
                
                // 执行SQL创建表结构
                // 使用外部SQL文件
                $sqlContent = file_get_contents('install/db_init.sql');
                
                // 更健壮的SQL语句分割方法，支持包含分号的注释和字符串
                $sqlStatements = preg_split('/;\s*$/m', $sqlContent);
                
                foreach ($sqlStatements as $statement) {
                    $trimmedStatement = trim($statement);
                    if (!empty($trimmedStatement)) {
                        try {
                            $pdo->exec($trimmedStatement);
                        } catch (PDOException $e) {
                            // 如果表已存在等错误，继续执行其他语句
                            if (strpos($e->getMessage(), 'already exists') === false) {
                                throw $e;
                            }
                        }
                    }
                }
                
                // 更新管理员账号 - 不使用加密方式存储密码
                $stmt = $pdo->prepare("UPDATE admin_users SET username = :username, password = :password, admin_qq = :qq WHERE id = 1");
                $stmt->execute([
                    ':username' => $adminUsername,
                    ':password' => $adminPassword,  // 直接存储明文密码，不加密
                    ':qq' => $adminQQ
                ]);
                        
                        // 备份原配置文件
                        $configPath = __DIR__ . '/config.php';
                        if (file_exists($configPath)) {
                            $backupPath = __DIR__ . '/config.php.bak.' . time();
                            if (!copy($configPath, $backupPath)) {
                                error_log('无法备份配置文件: ' . $configPath);
                            }
                        }
                        
                        // 生成配置文件
                        $configContent = sprintf($configTemplate, $dbConfig['host'], $dbConfig['port'], $dbConfig['name'], $dbConfig['user'], $dbConfig['pass']);
                        if (file_put_contents($configPath, $configContent) === false) {
                            throw new Exception('无法写入配置文件，请检查文件权限');
                        }
                        
                        // 更改配置文件权限
                        if (function_exists('chmod')) {
                            chmod($configPath, 0644);
                        }
                        
                        // 创建安装锁文件
                        $lockFilePath = __DIR__ . '/install.lock';
                        if (file_put_contents($lockFilePath, 'System installed on ' . date('Y-m-d H:i:s')) === false) {
                            throw new Exception('无法创建安装锁文件，请检查文件权限');
                        }
                        
                        // 更改锁文件权限
                        if (function_exists('chmod')) {
                            chmod($lockFilePath, 0644);
                        }
                        
                        // 保存安装成功状态
                        $installSuccess = true;
                        
                    } catch (PDOException $e) {
                        $error = '数据库操作失败: ' . $e->getMessage();
                        error_log('安装错误: ' . $error);
                        $installSuccess = false;
                    } catch (Exception $e) {
                        $error = '安装过程中出现错误: ' . $e->getMessage();
                        error_log('安装错误: ' . $error);
                        $installSuccess = false;
                    }
                    
                    if (!$installSuccess) {
                        echo "addLog('安装过程中出现错误: " . addslashes($error) . "', 'log-error');";
                        echo "setTimeout(() => { window.location.href = 'install.php?stage=admin&error=" . urlencode($error) . "'; }, 2000);";
                    } else {
                        echo "simulateInstallation();";
                    }
                    ?>
                });
            </script>
        <?php elseif ($stage === 'complete'): 
            // 检查是否已经显示过管理员信息（防止重复显示）
            if (isset($_SESSION['admin_info_displayed']) && $_SESSION['admin_info_displayed'] === true) {
                die('系统已安装完成，管理员信息已显示，如有需要请删除install.lock文件后重新安装。');
            }
            
            // 设置默认管理员信息
            $defaultUsername = 'admin';
            $defaultPassword = 'admin888';
            
            // 标记管理员信息已显示
            $_SESSION['admin_info_displayed'] = true;
            
            // 跳转到专门的管理员信息显示页面
            header('Location: install/show_admin_info.php');
            exit;
            
            // 输出15秒倒计时页面，显示默认账号密码
            ?>
            <!DOCTYPE html>
            <html lang="zh-CN">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>安装完成 - 管理员信息</title>
                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
                <style>
                    * {
                        margin: 0;
                        padding: 0;
                        box-sizing: border-box;
                    }
                    
                    body {
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                        min-height: 100vh;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        padding: 20px;
                    }
                    
                    .container {
                        background-color: white;
                        border-radius: 15px;
                        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
                        padding: 40px;
                        max-width: 500px;
                        width: 100%;
                        text-align: center;
                    }
                    
                    .logo {
                        font-size: 48px;
                        margin-bottom: 20px;
                        color: #667eea;
                    }
                    
                    .success-message {
                        margin-bottom: 30px;
                    }
                    
                    .success-message h1 {
                        color: #333;
                        margin-bottom: 10px;
                    }
                    
                    .success-message p {
                        color: #666;
                        font-size: 16px;
                    }
                    
                    .admin-details {
                        background-color: #f8f9fa;
                        border-radius: 10px;
                        padding: 25px;
                        margin-bottom: 30px;
                        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
                    }
                    
                    .admin-detail-item {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        padding: 12px 0;
                        border-bottom: 1px solid #eee;
                    }
                    
                    .admin-detail-item:last-child {
                        border-bottom: none;
                    }
                    
                    .admin-detail-label {
                        font-weight: 500;
                        color: #555;
                    }
                    
                    .admin-detail-value {
                        background-color: white;
                        padding: 6px 12px;
                        border-radius: 6px;
                        font-family: 'Courier New', monospace;
                        font-weight: 600;
                        color: #667eea;
                        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
                    }
                    
                    .countdown {
                        margin-bottom: 30px;
                        padding: 15px;
                        background-color: #fff3cd;
                        border: 1px solid #ffeaa7;
                        border-radius: 8px;
                        color: #856404;
                    }
                    
                    .countdown strong {
                        color: #d63031;
                        font-size: 20px;
                    }
                    
                    .notice {
                        background-color: #e3f2fd;
                        border-radius: 8px;
                        padding: 20px;
                        margin-bottom: 20px;
                        border-left: 4px solid #2196f3;
                        text-align: left;
                    }
                    
                    .notice p {
                        margin: 5px 0;
                        color: #333;
                    }
                    
                    .notice i {
                        color: #2196f3;
                        margin-right: 8px;
                    }
                    
                    .button-group {
                        display: flex;
                        gap: 15px;
                        justify-content: center;
                        margin-bottom: 20px;
                    }
                    
                    .btn {
                        padding: 12px 24px;
                        border: none;
                        border-radius: 8px;
                        font-size: 16px;
                        font-weight: 600;
                        cursor: pointer;
                        text-decoration: none;
                        transition: all 0.3s ease;
                    }
                    
                    .btn-primary {
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                        color: white;
                    }
                    
                    .btn-primary:hover {
                        transform: translateY(-2px);
                        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
                    }
                    
                    .btn-secondary {
                        background-color: #f8f9fa;
                        color: #667eea;
                        border: 1px solid #dee2e6;
                    }
                    
                    .btn-secondary:hover {
                        background-color: #e9ecef;
                    }
                    
                    .footer {
                        margin-top: 20px;
                        padding-top: 20px;
                        border-top: 1px solid #eee;
                        color: #666;
                        font-size: 14px;
                    }
                </style>
            </head>
            <body>
                <div class="container">
                    <div class="logo">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    
                    <div class="success-message">
                        <h1>安装完成</h1>
                        <p>系统已成功安装到您的服务器上</p>
                    </div>
                    
                    <div class="admin-details">
                        <div class="admin-detail-item">
                            <span class="admin-detail-label">用户名:</span>
                            <span class="admin-detail-value">admin</span>
                        </div>
                        <div class="admin-detail-item">
                            <span class="admin-detail-label">密码:</span>
                            <span class="admin-detail-value">admin888</span>
                        </div>
                    </div>
                    
                    <div class="countdown">
                        <p>此页面将在 <strong id="countdown-timer">15</strong> 秒后自动关闭，账号密码将不再显示</p>
                    </div>
                    
                    <div class="notice">
                        <p><i class="fas fa-info-circle"></i>请记住以上管理员账号和密码，登录后可以在后台修改</p>
                        <p><i class="fas fa-shield-alt"></i>为了安全起见，请及时修改默认密码</p>
                        <p><i class="fas fa-key"></i>此页面只显示一次，刷新后将不再显示账号密码信息</p>
                    </div>
                    
                    <div class="button-group">
                        <a href="../admin/" class="btn btn-primary">
                            <i class="fas fa-sign-in-alt"></i> 进入后台管理
                        </a>
                        <a href="../index.php" class="btn btn-secondary">
                            <i class="fas fa-home"></i> 返回首页
                        </a>
                    </div>
                    
                    <div class="footer">
                         © <?php echo date('Y'); ?> 订单自主查询系统
                      </div>
                </div>
                
                <script>
                    // 15秒倒计时
                    let countdown = 15;
                    const timerElement = document.getElementById('countdown-timer');
                    
                    const countdownInterval = setInterval(() => {
                        countdown--;
                        timerElement.textContent = countdown;
                        
                        if (countdown <= 0) {
                            clearInterval(countdownInterval);
                            // 倒计时结束后，跳转到首页
                            window.open('../install/delete_install_dir.php', '_blank');
                            window.location.href = '../index.php';
                        }
                    }, 1000);
                </script>
            </body>
            </html>
            <?php
            exit;
        endif; ?>
        
        <div class="footer">
             © <?php echo date('Y'); ?> 订单自主查询系统 - 安装向导
          </div>
    </div>
</body>
</html>